package apigateway.project.commen.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 * 将配置文件中的参数赋值到config中
 */
public class ConfigUtils {
    public static void toConfig(Properties prop,Object obj) {
        Method[] methods = obj.getClass().getMethods();
        for (Method method : methods) {
            String methodName = method.getName();
            if (methodName.startsWith("set")) {
               String key = methodName.substring(3, 4).toLowerCase() + methodName.substring(4);
                String property = prop.getProperty(key);
                if (property != null) {
                    //获取配置属性value的类型，set函数都是单参数
                    Class<?>[] parameterTypes = method.getParameterTypes();
                    Object arg = null;
                    if (parameterTypes.length == 1) {
                        if (parameterTypes[0] == String.class) {
                            arg = property;
                        }else if(parameterTypes[0] == Integer.class||parameterTypes[0]==int.class) {
                            arg = Integer.parseInt(property);
                        }else if(parameterTypes[0] == Double.class||parameterTypes[0]==double.class) {
                            arg = Double.parseDouble(property);
                        }else if(parameterTypes[0] == Float.class||parameterTypes[0]==float.class) {
                            arg = Float.parseFloat(property);
                        }else if(parameterTypes[0] == Long.class||parameterTypes[0]==long.class) {
                            arg = Long.parseLong(property);
                        }else if(parameterTypes[0] == Boolean.class||parameterTypes[0]==boolean.class) {
                            arg = Boolean.parseBoolean(property);
                        }else if(parameterTypes[0] == Byte.class||parameterTypes[0]==byte.class) {
                            arg = Byte.parseByte(property);
                        }
                        try {
                            method.invoke(obj,arg);
                        } catch (IllegalAccessException | InvocationTargetException ignored) {

                        }
                    }
                }
            }
        }
    }
}
